package org.geometerplus.fbreader.formats.m17k;

import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.example.administrator.fangbook.dataLibrary.book.IBookbase;
import com.example.administrator.fangbook.dataLibrary.book.ShelfItemBook;
import com.example.administrator.fangbook.read.bean.Chapter;

import org.geometerplus.fbreader.fbreader.FBReaderApp;
import org.geometerplus.fbreader.fbreader.FBView;
import org.geometerplus.fbreader.formats.BasicChapterReader;
import org.geometerplus.zlibrary.core.filesystem.ZL17KPlainTxtFile;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.text.model.ZLTextModel;
import org.geometerplus.zlibrary.text.view.ZLTextFixedPosition;
import org.geometerplus.zlibrary.text.view.ZLTextPosition;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.iwanvi.common.GlobalConstants.KEY_READ_STATE;

public class MTxtNovelReader extends BasicChapterReader {
    private static final String TAG = MTxtNovelReader.class.getSimpleName();

    public static final int CHAPTER_STATU_NONE = 0;
    public static final int CHAPTER_STATU_LOADING = 1;
    public static final int CHAPTER_STATU_END = 2;
    private static final int CHAPTER_PRESTRAIN_COUNT = 3; // 预加载章节数
    private int mChapterStatu;
    private Chapter mTmpChapter;
    private Object mObject = new Object();
    private boolean mIsLoadedChaptersFormNet = false;

    private long mLastDoLastChapterTime;
    private List<Chapter> mChapterList = null;

    public MTxtNovelReader(FBReaderApp app, ZLFile file) {
        super(app, file);
        mChapterStatu = CHAPTER_STATU_NONE;
        mChapterList = Collections.synchronizedList(new ArrayList<Chapter>(CHAPTER_PRESTRAIN_COUNT));
        VolumeUtils.getInstance().addCallback(mVolumeChangeListener);
        // LoadNotesManager.getInstance().addLoadNotesCallback(this);
    }

    @Override
    protected ZLFile createZLFile(String bookId, String bookName, String chapterId, String chapterName) {
        return new ZL17KPlainTxtFile(bookId, bookName, chapterId, chapterName);
    }


    @Override
    public void doFirstChapter() {
        final FBReaderApp reader = (FBReaderApp) FBReaderApp.Instance();
        reader.BookTextView.toastFirstPage();
    }

    @Override
    public void doLastChapter() {
        if (myBookModel.Book.File.getShelfBook().getBookType() != IBookbase.BookType.Type_ChineseAll) {
            FBReaderApp.Instance().getAppContext().onBackPressed();
            return;
        }
        // 处理快速翻页会多冷执行
        long time = System.currentTimeMillis();
        if (time - mLastDoLastChapterTime < 1000) {
            return;
        }
        mLastDoLastChapterTime = time;
        final FBReaderApp reader = (FBReaderApp) FBReaderApp.Instance();
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            ConnectUtil.get(UrlManager
                                    .getReportUserReadOverOneBookUrl(myBookModel.Book.File.getShelfBook().getBookId()));
                        } catch (ErrorMsgException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
//                reader.getAppContext().onBackPressed();
            }
        });

    }


    public void load() throws ErrorMsgException {
        myBookModel.mLoaded = false;
        // 加载本地目录
        loadChapters(false);
        // 异步加载笔记，完成后会调用onLoaded方法，通知更新UI
        // LoadNotesManager.getInstance().loadNotes(myBookId);
        myBookModel.mLoaded = true;
    }

//    @Override
//    public void onNotesLoaded(boolean result, String bookId, List<BookReadNote> notes) {
//        if (result && myBookId.equals(bookId)) {
//
//            if (myBookModel != null) {
//                myBookModel.setBookNotes(notes);
//                FBReaderApp fbReader = (FBReaderApp) FBReaderApp.Instance();
//                if (fbReader.BookTextView != null) {
//                    synchronized (mObject) {
//                        fbReader.BookTextView.loadZLSelectionData(myBookModel.getAllNotes(), myBookModel.getAllLocalUnderLineBlocks());
//                        if (fbReader.getViewWidget() != null) {
//                            FBReaderApp reader = (FBReaderApp) FBReaderApp.Instance();
//                            reader.getBookReader().getAnimationManager().postRunnableToRenderThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    FBReaderApp reader = (FBReaderApp) FBReaderApp.Instance();
//                                    if (reader != null) {
//                                        ZLTextWordCursor position = reader.BookTextView.getStartCursor();
//                                        if (position != null) {
//                                            position = new ZLTextWordCursor(position);
//                                        }
//                                        reader.clearTextCaches();
//                                        reader.BookTextView.setModel(reader.BookTextView.getModel(), position);
//                                    }
//                                }
//                            }, true);
//                        }
//                    }
//                }
//            }
//        }
//    }

//    @Override
//    public boolean isRunngingOnce() {
//        return true;
//    }


    private void volumes2Chapters(List<Volume> volumes) {
        if (volumes != null) {
            myChapters.clear();
            for (Volume v : volumes) {
                if (v.getChapters() != null) {
                    myChapters.addAll(v.getChapters());
                }
            }
            volumes.clear();
            volumes = null;
        }
    }

    /**
     * 主要用来获取本地存储的目录信息
     */
    private void loadChapters(boolean fromNet) {
        Context context = FBReaderApp.Instance().getAppContext();
        synchronized (myChapters) {
            mChapterStatu = CHAPTER_STATU_LOADING;
            VolumeListBean volumeBean = null;
            if (fromNet) {
                volumeBean = VolumeUtils.getInstance().getVolumeBeanFromServerBlock(context, myBookId, "", 0, -1);
            } else {
                // 读取本地缓存的
                if (myChapters.isEmpty()) {
                    if (!fromNet) {
                        volumeBean = VolumeUtils.getInstance().getVolumeBeanFromLocal(myBookId);
                    }
                    if (volumeBean == null || volumeBean.getVolumes() == null || volumeBean.getVolumes().isEmpty()) {
                        fromNet = true;
                        volumeBean = VolumeUtils.getInstance().getVolumeBeanFromServerBlock(context, myBookId, "", 0, -1);
                    }
                }
            }
            mChapterStatu = CHAPTER_STATU_END;
            if (volumeBean != null && volumeBean.getVolumes() != null) {
                if (fromNet) {
                    mIsLoadedChaptersFormNet = true;
                }
                volumes2Chapters(volumeBean.getVolumes());
                VolumeUtils.getInstance().sendMessage(myBookId, volumeBean.getVolumes(), false, volumeBean.getIsRed());
            }
        }
        if (!fromNet) {
            ShelfItemBook book = new ShelfItemBook(ShelfItemBook.isMiguBookId(myBookId) ? IBookbase.BookType.Type_Migu : IBookbase.BookType.Type_ChineseAll);
            book.setBookId(myBookId);
            VolumeUtils.getInstance().getVolumedata(context, book, false, true, mVolumeChangeListener);
        }
    }

    /**
     * 在已有目录列表中，通过章节id获取章节对象
     *
     * @param chapterId 章节id
     * @return Chapter
     */
    private Chapter getChapterById(String chapterId) {
        synchronized (myChapters) {
            Chapter chapter = null;
            if (!TextUtils.isEmpty(chapterId)) {
                for (Chapter c : myChapters) {
                    if (c.getId().equals(chapterId)) {
                        chapter = c;
                        break;
                    }
                }
            } else {
                if (!myChapters.isEmpty()) {
                    chapter = myChapters.get(0);
                }
            }
            if (chapter != null && TextUtils.isEmpty(chapter.getBookId())) {
                chapter.setBookId(getBookId());
            }
            return chapter;
        }
    }

    /**
     * 通过章节id去获取章节对象，如果没有目录列表，会请求获取目录列表
     *
     * @param chapterId 章节id
     * @return Chapter
     */
    public Chapter loadChapterById(String chapterId) {
        synchronized (myChapters) {
            Chapter chapter = null;
            if (TextUtils.isEmpty(chapterId)) {
                switch (mChapterStatu) {
                    case CHAPTER_STATU_NONE:
                        loadChapters(false);
                        chapter = getChapterById(chapterId);
                        break;
                    case CHAPTER_STATU_LOADING:
                    case CHAPTER_STATU_END:
                        chapter = getChapterById(chapterId);
                        break;
                }
            } else {
                if (myChapters.isEmpty()) {
                    mTmpChapter = new Chapter();
                    mTmpChapter.setBookId(myBookId);
                    mTmpChapter.setId(chapterId);
                    mTmpChapter.setName(myBookName);
                    if (mChapterStatu == CHAPTER_STATU_NONE) {
                        loadChapters(false);
                    }
                    chapter = mTmpChapter;
                } else {
                    chapter = getChapterById(chapterId);
                    if (chapter == null && !mIsLoadedChaptersFormNet) {
                        // 有可能目录不是最新的，需要重新从网络获取
                        loadChapters(true);
                        chapter = getChapterById(chapterId);
                    }
                }
            }
            return chapter;
        }
    }


    @Override
    public void destory() {
//        LoadNotesManager.getInstance().cancelLoadNotes(myBookId);
//        LoadNotesManager.getInstance().removeLoadNotesCallback(this);
        VolumeUtils.getInstance().removeCallback(mVolumeChangeListener);
    }

    private VolumeUtils.VolumeDataChangedInterface mVolumeChangeListener = new VolumeUtils.VolumeDataChangedInterface() {
        private long mLastTime = 0;

        @Override
        public void notifyChanged(String bookId, List<Volume> mVolumeArrayList, boolean mIsRefresh, int isRed) {
            if (myBookId.equals(bookId)) {
                long now = System.currentTimeMillis();
                // 忽略掉1s内的连续回调
                if (now - mLastTime < 1000) {
                    int count = 0;
                    if (mVolumeArrayList != null) {
                        for (Volume v : mVolumeArrayList) {
                            if (v.getChapters() != null) {
                                count += v.getChapters().size();
                            }
                        }
                    }
                    if (count == myChapters.size()) {
                        LogUtil.d(TAG, "mVolumeChangeListener 不要管我，我是打酱油的-->" + count);
                        return;
                    }
                }
                mLastTime = now;
                if (mVolumeArrayList != null && !mVolumeArrayList.isEmpty()) {
                    myChapters.clear();
                    for (Volume v : mVolumeArrayList) {
                        if (v.getChapters() != null) {
                            myChapters.addAll(v.getChapters());
                        }
                    }
                    LogUtil.d(TAG, "mVolumeChangeListener 章节总数：" + myChapters.size());
                    mChapterStatu = CHAPTER_STATU_END;
                    if (mTmpChapter != null) {
                        Chapter chapter = null;
                        // fixed 4.1.5 修复已加书架或阅读过的图书，有最新章节时，从H5目录购买后阅读，阅读器中章节显示不对的问题
                        // 首先加载本地目录，可能并没有现在阅读的章节，所以需要在没有获取到现在正常阅读章节的情况下，再次设置正在阅读的章节
                        Chapter nowChapter = getReadingChapter();
                        LogUtil.d(TAG, "mVolumeChangeListener nowChapter is null 1? " + (nowChapter == null));
                        if (nowChapter == null) {
                            chapter = gotoChapterById(mTmpChapter.getId());
                            LogUtil.d(TAG, "mVolumeChangeListener chapter is null? " + (nowChapter == null));
                            if (chapter != null) {
                                mTmpChapter.setName(chapter.getName());
                            }
                            nowChapter = getReadingChapter();
                            LogUtil.d(TAG, "mVolumeChangeListener nowChapter is null 2? " + (nowChapter == null));
                            if (nowChapter != null) {
                                mTmpChapter = null;
                            }
                        } else {
                            mTmpChapter = null;
                        }
                        FBReaderApp fbReader = (FBReaderApp) FBReaderApp.Instance();
                        if (fbReader.BookTextView != null && fbReader.getViewWidget() != null) {
                            if (chapter != null) {
                                synchronized (fbReader.BookTextView) {
                                    fbReader.Model.Book.setTitle(chapter.getName());
                                    fbReader.getViewWidget().repaintForcely();
                                }
                                readChapterSuccess(chapter);
                            }
                        }
                    }
                }
            }
        }

        @Override
        public void notifyFail(String bookId) {
            if (myBookId.equals(bookId)) {
                mChapterStatu = CHAPTER_STATU_NONE;
            }
        }
    };
    private final Runnable doGotoNextChapter = new Runnable() {
        @Override
        public void run() {
            MTxtNovelReader.super.gotoNextChapter();
        }
    };


    private List<AsyncTask> myRunningTasks = new ArrayList<AsyncTask>();

    @Override
    public void gotoNextChapter() {
        LogUtil.e("切章", "切换章节--开始切换下一章 --1、--MTxtNovelReader的gotoNextChapter()");
        gotoNextChapter(false);
    }

    private boolean isFileSave = false;

    @Override
    public void gotoNextChapter(boolean showLoading) {
        LogUtil.e("切章", "切换章节--开始切换下一章 --2、--MTxtNovelReader的gotoNextChapter(" + showLoading + ")");
        Chapter chapter = getNextChapter();
        if (chapter != null) {
            ZLFile file = createZLFile(myBookId, myBookName, chapter.getId(), chapter.getName());
            if (file.exists() && chapter.isVIP() != 0) {
                //章节状态 1:vip免费章节;2:全书购买;3:本章购买;4:本次限免;5:试读章节;6:免费章节;0:无阅读本章节权限
                LogUtil.e("切章", "切换章节--开始切换下一章 --2、--MTxtNovelReader的gotoNextChapter(" + showLoading + ")--本地文件存在并isVip！=0");
                super.gotoNextChapter();
            } else {
                if (file.exists()) {
                    isFileSave = true;
                    LogUtil.e("切章", "切换章节--开始切换下一章 --2、--MTxtNovelReader的gotoNextChapter(" + showLoading + ")--本地文件存在--" + isFileSave);
                } else {
                    isFileSave = false;
                }
                LogUtil.e("切章", "切换章节--开始切换下一章 --2、--MTxtNovelReader的gotoNextChapter(" + showLoading + ")--本地文件是否存在--" + isFileSave);
                DoReadAyncTask task = new DoReadAyncTask(chapter, doGotoNextChapter, showLoading, false);
                synchronized (myRunningTasks) {
                    myRunningTasks.add(task);
                }
                mChapterList.clear();
                mChapterList.add(chapter);
                AsyncTaskUtil.getInstance().execute(task, "");
            }
        } else {
            if (myApplication != null) {
                final FBView fbView = (FBView) myApplication.getCurrentView();
                fbView.stopPendingLoadPageData();
                fbView.initErrorInfo("章节文件不存在");
            }
        }
    }

    private Chapter getNextChapter(Chapter chapter) {
        if (chapter != null && myChapters != null && !myChapters.isEmpty()) {
            int idx = myChapters.indexOf(chapter);
            if (idx >= 0 && idx < myChapters.size() - 1) {
                return myChapters.get(idx + 1);
            }
        }
        return null;
    }

    /**
     * 用来缓存下一章节内容
     *
     * @param chapter Chapter
     */
    @Override
    public void readChapterSuccess(Chapter chapter) {
        if (chapter != null) {
            // 埋点：阅读的章节，过滤掉咪咕图书
            if (!ShelfItemBook.isMiguBookId(chapter.getBookId())) {
                LogItem item = new LogItem();
                item.setPft("3622");
                item.setDid(chapter.getBookId());
                item.setMsg(chapter.getId());
                StaticsLogService.sendLog(item);
                UploadData data = new UploadData();
                data.setChapterid(chapter.getId());
                data.setUploadtype(KConstants.READ_BOOK_TIME_TYPE);
                data.setSaveTime(System.currentTimeMillis());
                UploadManager.getsInstance().sendSaveDataMsg(data);
            }
            // 预加载
            Chapter nextChapter = getNextChapter(chapter);
            mChapterList.clear();
            for (int i = 0; i < CHAPTER_PRESTRAIN_COUNT; i++) {
                if (nextChapter != null) {
                    mChapterList.add(nextChapter);
                    nextChapter = getNextChapter(nextChapter);
                }
            }
            DoReadAyncTask task = new DoReadAyncTask(nextChapter, null, false, true);
            synchronized (myRunningTasks) {
                myRunningTasks.add(task);
            }
            AsyncTaskUtil.getInstance().execute(task, "");
//                ZLFile file = createZLFile(myBookId, myBookName, nextChapter.getId(), nextChapter.getName());
//                if (!file.exists()) {
//                }
        }
    }

    @Override
    public void gotoPreChapter(boolean toFirstPage) {
        LogUtil.e("切章", "切换章节--开始切换上一章 --1、--MTxtNovelReader的gotoPreChapter(boolean toFirstPage)");
        gotoPreChapter(toFirstPage, false);
    }

    @Override
    public void gotoPreChapter(final boolean toFirstPage, boolean showLoading) {
        LogUtil.e("切章", "切换章节--开始切换上一章 --2、--MTxtNovelReader的gotoPreChapter(" + toFirstPage + ", " + showLoading + ")");
        Chapter chapter = getPreviousChapter();
        if (chapter != null) {
            ZLFile file = createZLFile(myBookId, myBookName, chapter.getId(), chapter.getName());
            if (file.exists() && chapter.isVIP() != 0) {
                LogUtil.e("切章", "切换章节--开始切换上一章 --2、--MTxtNovelReader的gotoPreChapter(" + toFirstPage + ", " + showLoading + ")----文件存在并且isVip!=0");
                super.gotoPreChapter(toFirstPage);
            } else {
                if (file.exists()) {
                    LogUtil.e("切章", "切换章节--开始切换上一章 --2、--MTxtNovelReader的gotoPreChapter(" + toFirstPage + ", " + showLoading + ")----文件存在");
                    isFileSave = true;
                } else {
                    LogUtil.e("切章", "切换章节--开始切换上一章 --2、--MTxtNovelReader的gotoPreChapter(" + toFirstPage + ", " + showLoading + ")----文件不存在");
                    isFileSave = false;
                }
                final Runnable doGotoPrevChapter = new Runnable() {
                    @Override
                    public void run() {
                        MTxtNovelReader.super.gotoPreChapter(toFirstPage);
                    }
                };
                DoReadAyncTask task = new DoReadAyncTask(chapter, doGotoPrevChapter, showLoading, false);
                synchronized (myRunningTasks) {
                    myRunningTasks.add(task);
                }
                mChapterList.clear();
                mChapterList.add(chapter);
                // Log.e(TAG, "gotoPreChapter: read.run");
                AsyncTaskUtil.getInstance().execute(task, "");
            }
        } else {
            if (myApplication != null) {
                final FBView fbView = (FBView) myApplication.getCurrentView();
                fbView.stopPendingLoadPageData();
                fbView.initErrorInfo("章节文件不存在");
            }
        }
    }

    @Override
    public void gotoChapter(Chapter chapter, ZLTextPosition position) {
        ZL17KPlainTxtFile file = new ZL17KPlainTxtFile(myBookId, myBookName, chapter.getId(), chapter.getName());
        file.setBookId(myBookId);
        file.setBookName(myBookName);
        file.setChapterId(chapter.getId());
        file.setChapterName(chapter.getName());
        file.setStartPositioin(new ZLTextFixedPosition(0, 0, 0));
        gotoChapter(file, position);
    }

    @Override
    public void gotoChapter(final ZLFile file, final ZLTextPosition position) {
        LogUtil.e("切章", "点击书籍进入或者目录进入--MTxtNovelReader--gotoChapter(final ZLFile file, final ZLTextPosition position)");
        if (file == null) {
            if (myApplication != null) {
                final FBView fbView = (FBView) myApplication.getCurrentView();
                fbView.stopPendingLoadPageData();
                fbView.initErrorInfo("章节文件不存在");
            }
            return;
        }
        try {
            ZL17KPlainTxtFile m17KFile = (ZL17KPlainTxtFile) file;
            Chapter chapter = gotoChapterById(m17KFile.getChapterId());
            LogUtil.e("切章", "点击书籍进入或者目录进入--MTxtNovelReader--gotoChapter(final ZLFile file, final ZLTextPosition position)--file.exists()==" + file.exists() + ",,chapter.isVIP()==" + chapter.isVIP());
            if (file.exists() && chapter.isVIP() != 0) {
                super.gotoChapter(file, position);
            } else {
                if (file.exists()) {
                    isFileSave = true;
                } else {
                    isFileSave = false;
                }
                final Runnable doGotoChapter = new Runnable() {
                    @Override
                    public void run() {
                        ZL17KPlainTxtFile m17KFile = (ZL17KPlainTxtFile) file;
                        gotoChapterById(m17KFile.getChapterId());
                        MTxtNovelReader.super.gotoChapter(file, position);
                    }
                };
//            ZL17KPlainTxtFile m17kFile = (ZL17KPlainTxtFile) file;
//            Chapter chapter = new Chapter();
//            chapter.setId(m17kFile.getChapterId());
//            chapter.setName(m17kFile.getChapterName());
//            chapter.setBookId(m17kFile.getBookId());

                DoReadAyncTask task = new DoReadAyncTask(chapter, doGotoChapter);
                synchronized (myRunningTasks) {
                    myRunningTasks.add(task);
                }
                //Log.e(TAG, "gotoChapter: readTask。execute");
                mChapterList.clear();
                mChapterList.add(chapter);

                AsyncTaskUtil.getInstance().execute(task, "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class DoReadAyncTask extends AsyncTask<String, String, Boolean> {

        private Chapter mChapter;
        private Runnable mCb;
        private String errMsg = null;
        private boolean mNetError = false;
        private boolean myIsCanceled = false;
        private boolean mShowLoading;
        private boolean isCacheChapter;
        private ChapterContentV4 mContent;
        private boolean isFree;

        DoReadAyncTask(Chapter chapter, final Runnable freeCb) {
            this(chapter, freeCb, false, false);
        }

        DoReadAyncTask(Chapter chapter, final Runnable freeCb, boolean showLoading, boolean ischaptercache) {
            mChapter = chapter;
            mCb = freeCb;
            mShowLoading = showLoading;
            isCacheChapter = ischaptercache;
        }


        @Override
        protected void onCancelled() {
            super.onCancelled();
            myIsCanceled = true;
            synchronized (myRunningTasks) {
                myRunningTasks.remove(this);
            }
        }

        @Override
        protected Boolean doInBackground(String... params) {
            LogUtil.i(GlobalConstants.READER_LOG, "DoReadAyncTask  doInBackground 下载更多章节 ");
            for (int i = 0; i < mChapterList.size(); i++) {
                String[] strings = new String[1];
                strings[0] = mChapterList.get(i) != null ? mChapterList.get(i).getId() : mChapter.getId();
                isFree = Chapter.hasDownload(myBookId, strings[0]);
                LogUtil.e("切章", "切换章节--开始切换章 ----MTxtNovelReader的doInBackground()----文件是否存在1==" + isFree);
                if (isFree && isFileSave) {
                    isFree = false;
                }
                LogUtil.e("切章", "切换章节--开始切换章 ----MTxtNovelReader的doInBackground()----文件是否存在2==" + isFree);
                if (!isFree) {
                    try {
                        ArrayList<ChapterContentV4> v4s = (ArrayList<ChapterContentV4>) ChapterContent4Net.obtain(myBookId).getContentByChapters(strings);
                        if (v4s != null && v4s.size() > 0) {
                            mContent = v4s.get(0);
                        }
                        if (mContent != null) {
                            if (ShelfItemBook.isMiguBookId(mContent.getBookId())) {
                                if (mContent.getContents() != null) {
                                    isFree = true;
                                    mContent.setContents(null);
                                } else {
                                    // 自动购买
                                    if (!TextUtils.isEmpty(mContent.getPayUrl())) {
                                        ShelfItemBook book = BookshelfManager.getInstance().getBook(myBookId);
                                        if (book != null && book.getAutoBuyNextFlag() == ShelfItemBook.AUTO_BUY_NEXT_YES) {
                                            //mContent = MiGuRequestUtils.buyChapter(mContent.getPayUrl(), myBookId, mChapter.getId());
                                        }
                                    }
                                    if (mContent != null) {
                                        if (mContent.getContents() != null) {
                                            isFree = true;
                                            mContent.setContents(null);
                                        } else {
                                            isFree = false;
                                            mContent.setContents(null);
                                        }
                                    }
                                }
                            } else {
                                if (!TextUtils.isEmpty(mContent.getPayUrl())) {
                                    isFree = false;
//                                    mContent.setContents(null);
                                } else if (mContent.getContents() != null) {
                                    isFree = true;
//                                    mContent.setDescs(mContent.getContents());
                                    //章节状态 1:vip免费章节;2:全书购买;3:本章购买;4:本次限免;5:试读章节;6:免费章节;0:无阅读本章节权限
                                    switch (mContent.getChapterState()) {
                                        case 0:
                                            isFree = false;
                                            break;
                                        default:
                                            isFree = true;
                                            break;
                                    }

//                                    mContent.setContents(mContent);
                                } else {
                                    errMsg = "获取章节内容失败";
                                }
                            }
                        } else {
                            errMsg = "获取章节内容失败";
                        }


                    } catch (NetErrorException e) {
                        mNetError = true;
                        isFree = false;
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                        errMsg = e.getLocalizedMessage();
                    }
                }
            }

            return isFree;
        }


        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (isCacheChapter) {
                return;
            }
            FBReaderApp fbReaderApp = (FBReaderApp) FBReaderApp.Instance();
            if (fbReaderApp == null) {
                return;
            }
            ReadActivity activity = (ReadActivity) fbReaderApp.getAppContext();
            if (activity != null && !activity.isFinishing()) {
                activity.dismissLoading();
            }
            if (isCancelled() || myIsCanceled || activity.isFinishing()) {
                return;
            }
            synchronized (myRunningTasks) {
                myRunningTasks.remove(this);
            }

            //根据章节状态进行区分

            if (result) {
                mCb.run();
            } else {
                if (!mShowLoading) {
                    if (!myAnimationManager.isAnimating()) {
                        doAfterAnimation(mContent, mChapter);
                    } else {
                        myAnimationManager.setTurnPageHookCallBack(new Runnable() {
                            @Override
                            public void run() {
                                doAfterAnimation(mContent, mChapter);
                            }
                        });
                    }
                } else {
                    if (mContent == null) {
                        if (mNetError) {
                            errMsg = GlobalApp.getInstance().getString(R.string.comm_net_error);
                        }
                        if (TextUtils.isEmpty(errMsg)) {
                            errMsg = GlobalApp.getInstance().getString(R.string.txt_unknown_error);
                        }
                        ToastUtil.showToast(errMsg);
                    } else {
                        doAfterAnimation(mContent, mChapter);
                    }
                    mContent = null;
                }
            }
        }

        @Override
        protected void onPreExecute() {
            if (mShowLoading && !isCacheChapter) {
                ReadActivity activity = (ReadActivity) FBReaderApp.Instance().getAppContext();
                if (activity != null) {
                    activity.showLoading(activity.getString(R.string.txt_loading), true, new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            myIsCanceled = true;
                            synchronized (myRunningTasks) {
                                myRunningTasks.remove(this);
                            }
                        }
                    });
                }
            }
        }
    }

    public void doAfterAnimation(ChapterContentV4 mContent, Chapter mChapter) {
        if (myApplication != null) {
            ReadActivity activity = (ReadActivity) FBReaderApp.Instance().getAppContext();
            FBView fbView = (FBView) myApplication.getCurrentView();
            boolean needPay = false;
            if (mContent != null && activity != null) {
                needPay = true;
//                activity.showPayDialog(mContent, mChapter.getName());
            } else {

            }
            gotoChapterById(mChapter.getId());
            if (mContent != null) {
                fbView.initChapterTips(myBookId, mChapter, needPay, mContent.getPayType(), mContent.getBalance(), mContent.getPrice(), mContent.getDescs());
            } else {
                fbView.initChapterTips(myBookId, mChapter, needPay, 0, 0, 0, null);
            }

            ZLFile file = createZLFile(myBookId, myBookName, mChapter.getId(), mChapter.getName());
            ZLTextModel model = getModelByFile(file);
            myAnimationManager.setModel(file, model);
        }
        mContent = null;
    }
}
